#!/usr/bin/python3
import csv
import signal
from threading import Thread
from dlt import DLT
from flir_temp import FLIR_Temp

run_flag = True

class CSV_Logger(Thread):
    headers = ['col1', 'col2']
    def __init__(self, filename, datasrc):
        self.file = open(filename, 'w')
        self.writer = csv.writer(self.file)
        self.writer.writerow(self.headers)
        self.datasrc = datasrc
        super().__init__()

    def run(self):
        while run_flag:
            try:
                row = self.datasrc.read()
            except Exception:
                continue
            else:
                if row is None:
                    continue
                self.writer.writerow(row)
                self.file.flush()

    def close(self):
        self.file.close()

class DLT_logger(CSV_Logger):
    headers = ['ts', 'count', 'PWM', 'curr', 'volt', 'res']
    def __init__(self, filename='dlt.csv'):
        datasrc = DLT()
        super().__init__(filename, datasrc)

class FILR_logger(CSV_Logger):
    headers = ['ts', 'temp']
    def __init__(self, filename='flir.csv'):
        datasrc = FLIR_Temp()
        super().__init__(filename, datasrc)

dlt_log = DLT_logger()
flir_log = FILR_logger()
dlt_log.start()
flir_log.start()

def exit(signum, frame):
    print('SIGINT')
    run_flag = False
    dlt_log.join()
    flir_log.join()
    print('join OK')
    dlt_log.close()
    flir_log.close()

signal.signal(signal.SIGINT, exit)
